<template>
  <div class="forum-detail-container">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button icon="el-icon-arrow-left" @click="goBack">返回列表</el-button>
    </div>

    <!-- 帖子详情 -->
    <el-card class="post-detail-card" shadow="hover" v-if="post.id">
      <!-- 帖子头部 -->
      <div class="post-header">
        <h1 class="post-title">{{ post.title }}</h1>
        <div class="post-meta">
          <span class="meta-item">
            <i class="el-icon-user"></i>
            {{ post.username }}
          </span>
          <span class="meta-item">
            <i class="el-icon-time"></i>
            {{ formatTime(post.createTime) }}
          </span>
          <span class="meta-item">
            <i class="el-icon-thumb"></i>
            {{ post.likeCount }} 点赞
          </span>
          <span class="meta-item">
            <i class="el-icon-chat-dot-round"></i>
            {{ post.commentCount }} 评论
          </span>
        </div>
        <div class="post-keywords" v-if="post.keywords">
          <el-tag 
            v-for="(keyword, index) in post.keywords.split(',')" 
            :key="index"
            size="small"
            type="info">
            {{ keyword }}
          </el-tag>
        </div>
      </div>

      <!-- 帖子描述 -->
      <div class="post-description" v-if="post.description">
        {{ post.description }}
      </div>

      <!-- 帖子图片 -->
      <div class="post-images" v-if="post.images">
        <el-image
          v-for="(image, index) in post.images.split(',')"
          :key="index"
          :src="image"
          :preview-src-list="post.images.split(',')"
          fit="cover"
          class="post-image">
        </el-image>
      </div>

      <!-- 帖子正文 -->
      <div class="post-content">
        <pre>{{ post.content }}</pre>
      </div>

      <!-- 操作按钮 -->
      <div class="post-actions">
        <el-button 
          :type="isLiked ? 'danger' : 'primary'" 
          :icon="isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"
          @click="handleToggleLike">
          {{ isLiked ? '取消点赞' : '点赞' }}
        </el-button>
        <el-button 
          v-if="isAuthor"
          type="danger" 
          icon="el-icon-delete"
          @click="handleDeletePost">
          删除帖子
        </el-button>
      </div>
    </el-card>

    <!-- 评论区域 -->
    <el-card class="comment-section" shadow="hover">
      <div class="comment-header">
        <h3>评论区（{{ commentList.length }}）</h3>
      </div>

      <!-- 发表评论 -->
      <div class="add-comment">
        <el-input
          v-model="commentContent"
          type="textarea"
          :rows="3"
          placeholder="请输入评论内容..."
          maxlength="1000"
          show-word-limit>
        </el-input>
        <el-button 
          type="primary" 
          style="margin-top: 10px;"
          @click="handleAddComment">
          发表评论
        </el-button>
      </div>

      <!-- 评论列表 -->
      <div class="comment-list">
        <div 
          v-for="comment in commentList" 
          :key="comment.id"
          class="comment-item">
          <div class="comment-avatar">
            <i class="el-icon-user-solid"></i>
          </div>
          <div class="comment-content">
            <div class="comment-author">{{ comment.username }}</div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
          </div>
        </div>

        <el-empty v-if="commentList.length === 0" description="暂无评论，快来发表第一条评论吧~"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script>
import { 
  getPostById, 
  toggleLike, 
  checkLike, 
  addComment, 
  getCommentList,
  deletePost 
} from '@/api/forum'

export default {
  name: 'UserForumDetail',
  data() {
    return {
      postId: null,
      post: {},
      commentList: [],
      commentContent: '',
      isLiked: false,
      isAuthor: false
    }
  },
  mounted() {
    this.postId = this.$route.query.id
    if (this.postId) {
      this.loadPostDetail()
      this.loadCommentList()
      this.checkIfLiked()
    }
  },
  methods: {
    // 加载帖子详情
    async loadPostDetail() {
      try {
        const response = await getPostById(this.postId)
        if (response.data.code === 200) {
          this.post = response.data.data
          
          // 检查是否是作者
          const userInfo = JSON.parse(localStorage.getItem('userInfo'))
          this.isAuthor = userInfo.id === this.post.userId
        }
      } catch (error) {
        console.error('加载帖子详情失败', error)
        this.$notify.error({
          title: '错误',
          message: '加载帖子详情失败'
        })
      }
    },

    // 加载评论列表
    async loadCommentList() {
      try {
        const response = await getCommentList(this.postId)
        if (response.data.code === 200) {
          this.commentList = response.data.data
        }
      } catch (error) {
        console.error('加载评论列表失败', error)
      }
    },

    // 检查是否已点赞
    async checkIfLiked() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const userId = userInfo.id
        const response = await checkLike(this.postId, userId)
        if (response.data.code === 200) {
          this.isLiked = response.data.data
        }
      } catch (error) {
        console.error('检查点赞状态失败', error)
      }
    },

    // 点赞/取消点赞
    async handleToggleLike() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const userId = userInfo.id
        const response = await toggleLike(this.postId, userId)
        
        if (response.data.code === 200) {
          this.isLiked = response.data.data
          this.$notify.success({
            title: '成功',
            message: response.data.message
          })
          // 重新加载帖子详情以更新点赞数
          this.loadPostDetail()
        }
      } catch (error) {
        console.error('点赞操作失败', error)
        this.$notify.error({
          title: '错误',
          message: '操作失败'
        })
      }
    },

    // 发表评论
    async handleAddComment() {
      if (!this.commentContent.trim()) {
        this.$notify.warning({
          title: '提示',
          message: '请输入评论内容'
        })
        return
      }

      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const userId = userInfo.id
        const response = await addComment(
          this.postId,
          { content: this.commentContent },
          userId
        )

        if (response.data.code === 200) {
          this.$notify.success({
            title: '成功',
            message: '评论成功'
          })
          this.commentContent = ''
          // 重新加载评论列表和帖子详情
          this.loadCommentList()
          this.loadPostDetail()
        } else {
          this.$notify.error({
            title: '错误',
            message: response.data.message || '评论失败'
          })
        }
      } catch (error) {
        console.error('发表评论失败', error)
        this.$notify.error({
          title: '错误',
          message: '评论失败'
        })
      }
    },

    // 删除帖子
    handleDeletePost() {
      this.$confirm('确定要删除这篇帖子吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'))
          const userId = userInfo.id
          const response = await deletePost(this.postId, userId)

          if (response.data.code === 200) {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.goBack()
          } else {
            this.$notify.error({
              title: '错误',
              message: response.data.message || '删除失败'
            })
          }
        } catch (error) {
          console.error('删除帖子失败', error)
          this.$notify.error({
            title: '错误',
            message: '删除失败'
          })
        }
      }).catch(() => {})
    },

    // 返回列表
    goBack() {
      this.$router.push('/user/forum')
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.forum-detail-container {
  padding: 20px;
  min-height: calc(100vh - 130px);
}

.back-button {
  margin-bottom: 20px;
}

.post-detail-card {
  margin-bottom: 20px;
}

.post-header {
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.post-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.post-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.meta-item i {
  margin-right: 5px;
}

.post-keywords {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.post-description {
  font-size: 16px;
  color: #606266;
  line-height: 1.8;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
  margin-bottom: 20px;
}

.post-image {
  width: 100%;
  height: 200px;
  border-radius: 4px;
  cursor: pointer;
}

.post-content {
  font-size: 15px;
  line-height: 1.8;
  color: #303133;
  margin-bottom: 20px;
}

.post-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  margin: 0;
}

.post-actions {
  display: flex;
  gap: 10px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.comment-section {
  margin-bottom: 20px;
}

.comment-header {
  margin-bottom: 20px;
}

.comment-header h3 {
  font-size: 20px;
  color: #303133;
  margin: 0;
}

.add-comment {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #2c5f2d 0%, #1e4620 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 20px;
  margin-right: 15px;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-author {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.comment-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}
</style>

